package com.loan.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.entity.SysUser;
import com.loan.common.core.domain.model.LoginUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.OverConfigEntity;
import com.loan.system.mapper.OverConfigMapper;
import com.loan.system.mapper.SysUserMapper;
import com.loan.system.service.OverConfigService;
import com.loan.system.service.OverWeightService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author shiguang
 * @date 2022年09月26日 20:49
 */
@Service
@RequiredArgsConstructor
public class OverConfigServiceImpl implements OverConfigService {

    private final OverConfigMapper overConfigMapper;

    private final OverWeightService overWeightService;

    private final SysUserMapper sysUserMapper;

    @Override
    public TableDataInfo<OverConfigEntity> selectPageList(OverConfigEntity entity, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Map<String, Object> params = entity.getParams();
        LambdaQueryWrapper<OverConfigEntity> lqw = new LambdaQueryWrapper<OverConfigEntity>()
                .eq(ObjectUtil.isNotNull(loginUser.getCompanyId()), OverConfigEntity::getCompanyId, loginUser.getCompanyId())
                .eq(OverConfigEntity::getDelFlag, "0")
                .orderByAsc(OverConfigEntity::getMaxDay);
        Page<OverConfigEntity> page = overConfigMapper.selectPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    @Override
    public OverConfigEntity selectById(Long id) {
        OverConfigEntity overConfigEntity = overConfigMapper.selectById(id);
        //获取绑定的用户ID
        List<Long> userIds = overConfigMapper.selectUserIdsById(id);
        overConfigEntity.setUserIds(userIds);
        return overConfigEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(OverConfigEntity entity) {
        entity.setCompanyId(LoginHelper.getLoginUser().getCompanyId());
        return overConfigMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(OverConfigEntity entity) {
        return overConfigMapper.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        //获取该配置是否绑定了催收用户
        List<Long> userIds = overConfigMapper.selectUserIdsById(id);
        if (CollectionUtils.isEmpty(userIds)){
            return 0;
        }
        return overConfigMapper.deleteById(id);
    }

    @Override
    public List<Long> getUserIdsById(Long id) {
        List<Long> userIds = overConfigMapper.selectUserIdsById(id);
        return userIds;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOverUserIds(JSONObject jsonObject) {
        Long id = jsonObject.getLong("id");
        List userIds = jsonObject.getJSONArray("userIds");
//        if (id == null || CollectionUtil.isEmpty(userIds)) {
//            overConfigMapper.deleteUserConfigById(id);
//            return 1;
//        }
        //先删除  后添加
        overConfigMapper.deleteUserConfigById(id);
        if (id != null && !CollectionUtil.isEmpty(userIds)) {
            overConfigMapper.addUserConfig(id, userIds);
            //修改权重分配 如果取消某催收人员  则权限中的催收人员也相应删掉
            overWeightService.deleteUserIdNotInId(id, userIds);
        }
        return 1;
    }

    @Override
    public List<Long> selectByUserId(Long userId) {
        return overConfigMapper.selectByUserId(userId);
    }

    @Override
    public List<OverConfigEntity> selectList(Long companyId) {
        return overConfigMapper.selectList(new QueryWrapper<OverConfigEntity>()
                .eq("company_id", companyId)
                .eq("del_flag", "0")
                .orderByAsc("id"));
    }

    @Override
    public int selectByCompanyId(Long companyId) {
        return overConfigMapper.selectMinDayByCompanyId(companyId);
    }

    @Override
    public List<SysUser> getListOverUserIds(String beginTime, String endTime) {
        List<Long> ids = new ArrayList<>();
        List<SysUser> users = new ArrayList<>();
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            Date startDate = DateUtils.parseDate(beginTime);
            Date endDate = DateUtils.parseDate(endTime);
            long days = DateUtil.between(startDate, DateUtil.beginOfDay(new Date()), DateUnit.DAY);
            long endDays = DateUtil.between(endDate, DateUtil.beginOfDay(new Date()), DateUnit.DAY);
            if (startDate.after(DateUtil.beginOfDay(new Date()))) {
                days = 0 - days;
            }
            if (endDate.after(DateUtil.beginOfDay(new Date()))) {
                endDays = 0 - endDays;
            }

            //获取该公司催收配置
            List<OverConfigEntity> configEntityList = selectList(LoginHelper.getCompanyId());
            if (!CollectionUtils.isEmpty(configEntityList)) {
                for (OverConfigEntity overConfigEntity : configEntityList) {
                    if (endDays < 0 && overConfigEntity.getMinDay() < 0) {
                        List<Long> userIds = getUserIdsById(overConfigEntity.getId());
                        if(!CollectionUtils.isEmpty(userIds)){
                        ids.addAll(userIds);
                        }
                    } else if (overConfigEntity.getMinDay() <= endDays && overConfigEntity.getMaxDay() >= endDays) {
                        //根据配置查找匹配的催收人员
                        List<Long> userIds = getUserIdsById(overConfigEntity.getId());
                        if(!CollectionUtils.isEmpty(userIds)){
                            ids.addAll(userIds);
                        }
                    } else if (overConfigEntity.getMaxDay() >= days && overConfigEntity.getMinDay() <= days) {
                        List<Long> userIds = getUserIdsById(overConfigEntity.getId());
                        if(!CollectionUtils.isEmpty(userIds)){
                            ids.addAll(userIds);
                        }
                    }
                }
            }
        } else {
            List<OverConfigEntity> configEntityList = selectList(LoginHelper.getCompanyId());
            if (!CollectionUtils.isEmpty(configEntityList)) {
                for (OverConfigEntity overConfigEntity : configEntityList) {
                    List<Long> userIds = getUserIdsById(overConfigEntity.getId());
                    if(!CollectionUtils.isEmpty(userIds)){
                        ids.addAll(userIds);
                    }
                }
            }
        }
        for (Long id :ids){
            SysUser sysUser = sysUserMapper.selectById(id);
            if (ObjectUtil.isNotNull(sysUser)) {
                users.add(sysUser);
            }
        }
        return users;
    }

    /**
     * 催收配置获取催收员列表
     * @param id 配置id
     * @return
     */
    @Override
    public List<SysUser> getOverUserList(Long id) {
        List<Long> ids = new ArrayList<Long>();
        //该配置绑定的用户id
        List<Long> userIds = new ArrayList<Long>();

        List<SysUser> users = new ArrayList<>();
        //改平台下绑定的催收用户
        List<Long> uIds = new ArrayList<Long>();
        Long companyId = LoginHelper.getCompanyId();
        if (!ObjectUtils.isEmpty(companyId)){
            //获取已绑定的催收员
            List<OverConfigEntity> configEntityList = selectList(companyId);
            //已经绑定的用户

            for (OverConfigEntity overConfigEntity : configEntityList) {
                uIds = getUserIdsById(overConfigEntity.getId());
                if(!CollectionUtils.isEmpty(uIds)){
                    ids.addAll(uIds);
                }
            }

            if (id != null && id != 0){
                //获取该配置下绑定的用户
                userIds = getUserIdsById(id);
            }

            //获取该公司所有的催收人员
            List<SysUser> sysUsers = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                    .eq("company_id", companyId)
                    .eq("collection", "1")
                    .eq("del_flag", "0")
                    .eq("status", "0")
            );

           for (SysUser sysUser : sysUsers){
               if(!ids.contains(sysUser.getUserId())){
                   users.add(sysUser);
               }
           }
            for (SysUser sysUser : sysUsers){
                if(userIds.contains(sysUser.getUserId())){
                    users.add(sysUser);
                }
            }

        }
        return users;
    }
}
